import { createRequire } from "module"
import fs from "node:fs"
import moment from "moment"
import { Plugin_Path, Config, Version } from "#yenai.components"
import request from "#yenai.request"
import { formatDuration } from "../../tools/index.js"
// import { getImgPalette } from "./utils.js"

const require = createRequire(import.meta.url)

export default async function getBotState(e) {
  const botList = _getBotList(e)
  const dataPromises = botList.map(async (i) => {
    const bot = Bot[i]
    if (!bot?.uin) return false

    const { nickname, status, apk, version } = bot

    // 头像
    const avatarUrl = bot.avatar ?? (Number(bot.uin) ? `https://q1.qlogo.cn/g?b=qq&s=0&nk=${bot.uin}` : "default")
    const avatar = await getAvatarColor(avatarUrl)

    const verKey = e.isPro ? "version" : "ver"
    const platform = apk
      ? `${apk.display} v${apk?.[verKey] || apk[!e.isPro ? "version" : "ver"]}`
      : version?.version ?? "未知"

    const messageCount = await getMessageCount(bot)

    const countContacts = getCountContacts(bot)

    const botRunTime = formatDuration(Date.now() / 1000 - bot.stat?.start_time, "dd天hh时mm分ss秒", true)

    const botVersion = version
      ? `${version.name}${version?.version ? ` ${version.version}` : ""}`
      : `ICQQ v${require("icqq/package.json").version}`

    return {
      avatar,
      nickname: nickname ?? "未知",
      botRunTime: `Bot已运行 ${botRunTime}`,
      status: status ?? 11,
      platform,
      botVersion,
      messageCount,
      countContacts
    }
  })
  let data

  if (e.isPro && Config.state?.yunzai) {
    data = await Promise.all(dataPromises).then(r => r.filter(Boolean))
    let sent = 0,
      recv = 0,
      screenshot = 0,
      friend = 0,
      group = 0,
      groupMember = 0

    const getNum = (i) => Number(String(i).match(/\d+/)?.[0] || 0)

    for (let i of data) {
      sent += getNum(i.messageCount.sent)
      recv += getNum(i.messageCount.recv)
      screenshot += getNum(i.messageCount.screenshot)
      friend += getNum(i.countContacts.friend)
      group += getNum(i.countContacts.group)
      groupMember += getNum(i.countContacts.groupMember)
    }

    // 获取已加载适配器数量
    let adapterNum = 0
    if (Bot?.adapter && Array.isArray(Bot.adapter)) {
      adapterNum = Bot.adapter.filter(i => typeof i === "object").length
    }

    data.unshift({
      avatar: await getAvatarColor("default"),
      nickname: Version.name,
      botRunTime: `已加载适配器：${adapterNum}个`,
      status: 11,
      platform: `${Version.name} ${Version.yunzai}`,
      botVersion: `已连接账号数量：${botList.length}个`,
      messageCount: {
        sent: formatCount(sent, "发送："),
        recv: formatCount(recv, "接收："),
        screenshot: formatCount(screenshot, "图片：")
      },
      countContacts: {
        friend: formatCount(friend, "好友："),
        group: formatCount(group, "群："),
        groupMember: formatCount(groupMember, "群员：")
      }
    })
  } else {
    data = Promise.all(dataPromises).then(r => r.filter(Boolean))
  }

  return data
}

function formatCount(value, prefix) {
  return value ? `${prefix}${value}` : 0
}

async function getAvatarColor(url) {
  const defaultAvatar = `${Plugin_Path}/resources/state/img/default_avatar.jpg`
  try {
    if (url == "default") {
      // 随机头像
      let txurl = `${process.cwd()}/resources/Avatar/`
      if (fs.existsSync(txurl)) {
        let tx_img = []
        for (let txlb of fs.readdirSync(txurl)) {
          if (txlb.includes(".")) {
            tx_img.push(txurl + txlb)
          }
        }
        if (tx_img.length > 0) {
          url = tx_img[Math.floor(Math.random() * tx_img.length)]
        }
      } else {
        url = defaultAvatar
      }
    } else if (Config.state.avatarDownloader) {
      const buffBase64 = await request.get(url, {
        responseType: "arrayBuffer"
      })
      url = `data:image/jpeg;base64,${Buffer.from(buffBase64).toString("base64")}`
    }
    return {
      path: url
    }
  } catch (err) {
    logger.error("[Yenai-Plugin][状态]解析头像失败：", err)
    return {
      similarColor1: "#fff1eb",
      similarColor2: "#ace0f9",
      path: url
    }
  }
}

async function getMessageCount(bot) {
  const nowDate = moment().format("MMDD")
  const keys = [
    `Yz:count:send:msg:bot:${bot.uin}:total`,
    `Yz:count:receive:msg:bot:${bot.uin}:total`,
    `Yz:count:send:image:bot:${bot.uin}:total`,
    `Yz:count:screenshot:day:${nowDate}`
  ]

  const values = await redis.mGet(keys) || []

  const sent = values[0] || bot.stat?.sent_msg_cnt
  const recv = values[1] || bot.stat?.recv_msg_cnt
  const screenshot = values[2] || values?.[3]

  return {
    sent: formatCount(sent, "发送："),
    recv: formatCount(recv, "接收："),
    screenshot: formatCount(screenshot, "图片：")
  }
}

function getCountContacts(bot) {
  const groupMember = Array.from(bot.gml?.values() || []).reduce((acc, curr) => acc + curr.size, 0)
  return {
    friend: formatCount(bot.fl?.size, "好友："),
    group: formatCount(bot.gl?.size, "群："),
    groupMember: formatCount(groupMember, "群员：")
  }
}

function _getBotList(e) {
  /** bot列表 */
  let BotList = [e?.bot?.uin || e.self_id || Bot.uin]

  if (Bot?.uin2) {
    if (e.isPro) {
      if (Array.isArray(Bot.uin2)) {
        /** TRSS */
        for (let i of Bot.adapter) {
          if (i && typeof i === 'string' && !Bot.uin2.includes(i)) {
            Bot.uin2.push(i)
          }
        }
        BotList = Bot.uin2
      } else if (!Array.isArray(Bot.uin2) && Bot.adapter && Bot.adapter?.includes(e.bot.uin)) {
        /** ws-plugin、Lain-plugin多bot */
        BotList = Bot.adapter
      }
    }
  } else {
    if (e.isPro) {
      if (Array.isArray(Bot.uin)) {
        /** TRSS */
        BotList = Bot.uin
      } else if (Bot.adapter && Bot.adapter?.includes(e.self_id)) {
        /** ws-plugin、Lain-plugin多bot */
        BotList = Bot.adapter
      }
    }
  }

  return BotList
}
